<template>
  <div ref="trendCanvas" class="trendCanvas"></div>
  <div ref="canvas" class="trendCanvas"></div>
</template>
<script setup>
  import * as echarts from 'echarts';

  import { useRoute } from 'vue-router';
  import { ref, inject, watch, onMounted, onUnmounted } from 'vue';

  import helpers from '@/libs/helpers';
  import refresher from '@/libs/autoRefreshShares';

  const $route = useRoute();
  const $http = inject('$http');

  const trendCanvas = ref();
  const canvas = ref([]);

  const shares = ref([]);
  const currentShare = ref('');
  const chartTitle = ref('');

  let echartsInstance = null;
  const intervalHandlers = [];
  const echartsOption = {
    title: {
      text: ''
    },
    grid: {
      left: '30px',
      right: '30px',
      bottom: '10px',
      top: '70px',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        animation: true
      },
      formatter: function (params) {
        let result = `${params[0].name}<br />`;

        params.forEach(item => {
          let unit = item.seriesName == '涨幅' ? '%' : '元';

          result += `<p class="chart-tooltip-line"><b>${item.marker}${item.seriesName}</b> <b>${item.value} ${unit}</b></p>`;
        });

        return result;
      }
    },
    legend: {
      right: '20px',
      data: ['当前价', '涨幅']
    },
    toolbox: {
      show: false
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      axisLabel: {
        formatter: '{value}'
      },
      axisPointer: {
        show: true,
        label: {
          show: true,
          formatter: '{value}'
        }
      },
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '价格(元)',
        min: 0,
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '涨幅(%)',
        min: -20,
        max: 20,
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '当前价',
        type: 'line',
        smooth: true,
        yAxisIndex: 0,
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }]
        }
      },
      {
        name: '涨幅',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }]
        },
        itemStyle: {
          color: function (params) {
            if (params.value > 0) {
              return '#C1232B';
            } else {
              return 'green';
            }
          }
        }
      }
    ],
    visualMap: {
      show: false,
      // 只对第二条线进行设置
      seriesIndex: 1,
      textStyle: {
        color: '#000'
      },
      pieces: [
        { min: 0, max: 2000000, label: '涨', color: '#C1232B' },
        { min: -20000, max: 0, label: '跌', color: 'green' }
      ],
      outOfRange: {
        color: 'green'
      }
    }
  };

  let echartsInstance2 = null;
  const echartsOption2 = {
    grid: {
      left: '15px',
      right: '15px',
      bottom: '0',
      top: '35px',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        animation: true
      },
      formatter: function (params) {
        let result = `${params[0].name}<br />`;

        params.forEach(item => {
          let unit = item.seriesName == '涨幅' ? '%' : '元';

          result += `<p class="chart-tooltip-line"><b>${item.marker}${item.seriesName}</b> <b>${item.value} ${unit}</b></p>`;
        });

        return result;
      }
    },
    legend: {
      align: 'left',
      data: ['价格', '涨幅']
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        formatter: '{value}'
      },
      axisPointer: {
        show: true,
        label: {
          show: true,
          formatter: '{value}'
        }
      },
      data: []
    },
    yAxis: [
      {
        type: 'value',
        name: '价格(元)',
        min: 0,
        position: 'left',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '涨幅(%)',
        position: 'right',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '价格',
        type: 'line',
        smooth: true,
        yAxisIndex: 0,
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: '平均值' }]
        }
      },
      {
        name: '涨幅',
        type: 'line',
        smooth: true,
        yAxisIndex: 1,
        data: [],
        itemStyle: {
          color: function (params) {
            if (params.value > 0) {
              return '#C1232B';
            } else {
              return 'green';
            }
          }
        }
      }
    ],
    visualMap: {
      show: false,
      // 只对第二条线进行设置
      seriesIndex: 1,
      textStyle: {
        color: '#000'
      },
      pieces: [
        { min: 0, max: 2000000, label: '涨', color: '#C1232B' },
        { min: -20000, max: 0, label: '跌', color: 'green' }
      ],
      outOfRange: {
        color: 'green'
      }
    }
  };

  async function renderCurrentDayMetric() {
    if (!echartsInstance) {
      echartsInstance = echarts.init(trendCanvas.value);

      // 使用刚指定的配置项和数据显示图表。
      echartsInstance.setOption(echartsOption);
    }

    let rs = await $http.get(`/api/shares/${currentShare.value}/statistics`, { hideTip: true });

    const d = rs.datas;

    echartsOption.xAxis.data = d.map(function (m) {
      return `${m.Time}`;
    });

    echartsOption.series[0].data = d.map(function (m) {
      return m.CurrentPrice.toFixed(2);
    });

    echartsOption.series[1].data = d.map(function (m) {
      return (((m.CurrentPrice - m.YesterdayPrice) / m.YesterdayPrice) * 100).toFixed(2);
    });

    if (echartsInstance) {
      // 使用刚指定的配置项和数据显示图表。
      echartsInstance.setOption(echartsOption);
    }
  }

  async function renderDailyMetric() {
    if (!echartsInstance2) {
      echartsInstance2 = echarts.init(canvas.value);

      // 使用刚指定的配置项和数据显示图表。
      echartsInstance2.setOption(echartsOption2);
    }

    let res = await $http.get(`/api/shares/${currentShare.value}/prices`, { hideTip: true });

    let d = res.datas;

    echartsOption2.xAxis.data = d.map(function (m) {
      return `${m.Date}`;
    });

    echartsOption2.series[0].data = d.map(function (m) {
      return m.CurrentPrice.toFixed(2);
    });

    echartsOption2.series[1].data = d.map(function (m) {
      return (((m.CurrentPrice - m.StartPrice) / m.StartPrice) * 100).toFixed(2);
    });

    // 使用刚指定的配置项和数据显示图表。
    echartsInstance2.setOption(echartsOption2);
  }

  watch($route, () => {
    currentShare.value = $route.params.code;
  });

  watch(currentShare, val => {
    let item = shares.value.find(d => d.value == val);

    if (item) {
      chartTitle.value = item.label;
    }
  });

  onMounted(() => {
    currentShare.value = $route.params.code;
    echartsOption.title.text = helpers.dateFormat(new Date(), 'MM-dd hh:mm:ss');

    intervalHandlers.forEach(handler => clearInterval(handler));
    intervalHandlers.length = 0;

    renderDailyMetric();
    renderCurrentDayMetric();

    refresher.start({
      step() {
        renderDailyMetric();
        renderCurrentDayMetric();
      }
    });
  });

  onUnmounted(() => {
    refresher.stop();

    echartsInstance = null;
  });
</script>
<style lang="less" scoped>
  .trendCanvas {
    width: 100%;
    display: inline-block;
    background: #fff;
    border-radius: 5px;
    padding: 5px 10px;
    height: 320px;
    margin-top: 0;

    &:not(:first-of-type) {
      margin-top: 5px;
    }

    > div {
      width: 100% !important;
    }
  }
</style>
